﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace NETFramwork_Dev
{
    public partial class Frm_Main : Form
    {
        public Frm_Main()
        {
            InitializeComponent();
        }

        #region 扫描IP
        private void btn_search_ip_Click(object sender, EventArgs e)
        {
            StringBuilder ip_list = new StringBuilder(10240);
            // 搜索当前网段的IP地址
            var res = ZMCAUX.ZAux_SearchEthlist(ip_list, 10239, 500);
            if (res != 0)
            {
                MessageBox.Show("搜索失败");
                return;
            }
            // 获取ip字符串
            string ip_str = "127.0.0.1 " + ip_list.ToString(); // 127.0.0.1 127.0.0.1 
            // 把ip拆分为数组
            string[] ips = ip_str.Split(' ');
            // 拆分结果绑定到下拉列表
            cmb_ip.DataSource = ips;
        }
        #endregion

        #region 连接控制器
        IntPtr z_handle = IntPtr.Zero;
        private void btn_connect_Click(object sender, EventArgs e)
        {
            // 先关闭控制器
            if (z_handle != IntPtr.Zero)
            {
                CloseConnect(z_handle);
            }
            // 再打开控制器连接
            string ip = cmb_ip.Text;
            int res = ZMCAUX.ZAux_FastOpen(2, ip, 1000, out z_handle);
            if(res != 0)
            {
                MessageBox.Show("连接控制器失败");
            }
            else
            {
                this.Text = "已连接";
                MessageBox.Show("连接控制器成功");
            }
        }

        // 关闭连接
        public int CloseConnect(IntPtr z_handle)
        {
            return ZMCAUX.ZAux_Close(z_handle);
        }
        #endregion

        private void Frm_Main_FormClosed(object sender, FormClosedEventArgs e)
        {
            CloseConnect(z_handle);
        }
    }
}
